package com.sdx.console.contract.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.contract.entity.*;
import com.sdx.console.contract.service.*;
import com.sdx.console.contract.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * ContractInfo 接口
 */
@RequestMapping("/contract/contractInfo")
@Controller
public class ContractInfoController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(ContractInfoController.class);
    private static final String MODEL = "/contract/contractInfo";


    @Resource
	private ContractInfoService contractInfoService;
    @Resource
    private CustomerInfoService customerInfoService;
    @Resource
    private SQLManager sqlManager;
    @Resource
    private CorePlatformService platformService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setIsTeacher(1);
        List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
        view.addObject("customerInfoList",customerInfoList);
        view.addObject("customerList", JSON.toJSONString(customerInfoList));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("contract.contractInfo.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("contract.contractInfo.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer contractId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        ContractInfo contractInfo = contractInfoService.queryById(contractId);
        view.addObject("contractInfo", contractInfo);
		setPageParam(view,request);
		try {
			view.addObject("contractInfoJson", JacksonUtils.toJsonString(contractInfo,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        List<String> list= contractInfoService.selectContractMemberById(contractId);
		if(list.size()>0){
		    StringBuffer customerIds = new StringBuffer();
            for (String customerId:list) {
                customerIds.append("'").append(customerId).append("',");
            }
            customerIds.deleteCharAt(customerIds.length() - 1);
            view.addObject("selectedMerber", customerIds);
        }


        return view;
    }

    @GetMapping("/add.do")
    @Function("contract.contractInfo.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("contract.contractInfo.query")
    @ResponseBody
    public JsonResult<PageQuery> list(ContractInfo condtion,HttpServletRequest request)
    {

        Integer accessType = platformService.getAccessType(request);
        CoreUser user = getLoginUser(request);
        //accessType 1，查看本人，3，查看本部门，6，查看全公司
        if(accessType==1){
            condtion.setUserId(user.getId());
        }else if(accessType==3){
            condtion.setOrgId(user.getOrgId());
        }

        PageQuery page = condtion.getPageQuery();
        contractInfoService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,ContractInfo contractInfo,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			contractInfo.setCreateDate(new Date());
			contractInfoService.save(contractInfo);
		} else {
            ContractInfo contract = new ContractInfo();
            contract.setContractId(contractInfo.getContractId());
            contract.setServant(contractInfo.getServant());
            contract.setUpdatedBy(user.getId().intValue());
            contract.setUpdatedName(user.getName());
            contract.setUpdatedTime(new Date());
            contract.setRemark(contractInfo.getRemark());
			contractInfoService.updateTemplate(contract);
            contractInfoService.delBatchContractMember(contractInfo.getContractId());
            List<CustomerInfo> list = contractInfoService.selectCustomerInfo("'"+contractInfo.getContractMember().replaceAll(",","','")+"'");
            List<ContractMember> memberList = new ArrayList<>();
            for (CustomerInfo info:list) {
                ContractMember member = new ContractMember();
                member.setContractId(contractInfo.getContractId());
                member.setUserId(info.getCustomerId());
                member.setUserName(info.getCustomerName());
                memberList.add(member);
            }
            if(memberList.size()>0){
                contractInfoService.insertContractMember(memberList);
            }
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("contract.contractInfo.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ContractInfo contractInfo,HttpServletRequest request
		)
    {

        return save(true,contractInfo,request
		);
    }

    @PostMapping("/update.json")
    @Function("contract.contractInfo.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ContractInfo contractInfo,HttpServletRequest request
		) {
		return save(false,contractInfo,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("contract.contractInfo.query")
    @ResponseBody
    public JsonResult<ContractInfo>queryInfo(Integer contractId) {
        ContractInfo contractInfo = contractInfoService.queryById( contractId);
        return  JsonResult.success(contractInfo);
    }

//    @PostMapping("/delete.json")
//    @Function("contract.contractInfo.del")
//    @ResponseBody
//    public JsonResult delete(String ids) {
//		List<String> idList = Utils.strToList(ids,",");
//        contractInfoService.batchDelContractInfo(idList);
//        return JsonResult.success();
//    }
    @PostMapping("/delete.json")
    @Function("contract.contractInfo.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        System.out.println(ids);
		List<String> idList = Utils.strToList(ids,",");
        for (String id : idList){
            ContractInfo contractInfo = sqlManager.query(ContractInfo.class).andEq("contract_id",id).single();
            if (contractInfo == null){
                return JsonResult.loginFail("1001","订单号 "+id+" 为空");
            }
            contractInfo.setHtStatus(3);
            sqlManager.updateTemplateById(contractInfo);
        }

        return JsonResult.success();
    }

    @PostMapping("/confirm.json")
    @Function("contract.contractInfo.confirm")
    @ResponseBody
    public JsonResult confirm(String ids) {
        List<String> idList = Utils.strToList(ids,",");
        contractInfoService.fkStatusContractInfoByIds(2,idList);
        toVip(ids);
        return JsonResult.success();
    }

    @PostMapping("/applyRefund.json")
    @Function("contract.contractInfo.applyRefund")
    @ResponseBody
    public JsonResult applyRefund(Integer contractId) {
        ContractInfo contractInfo  = new ContractInfo();
        contractInfo.setContractId(contractId);
        contractInfo.setTkStatus(1);
        contractInfoService.updateTemplate(contractInfo);
        return JsonResult.success();
    }

    @PostMapping("/auditRefund.json")
    @Function("contract.contractInfo.auditRefund")
    @ResponseBody
    public JsonResult auditRefund(Integer contractId) {
        ContractInfo contractInfo  = new ContractInfo();
        contractInfo.setContractId(contractId);
        contractInfo.setTkStatus(2);
        contractInfoService.updateTemplate(contractInfo);
        return JsonResult.success();
    }

    @PostMapping("/confirmRefund.json")
    @Function("contract.contractInfo.confirmRefund")
    @ResponseBody
    public JsonResult confirmRefund(Integer contractId) {
        ContractInfo contractInfo  = new ContractInfo();
        contractInfo.setContractId(contractId);
        contractInfo.setTkStatus(3);
        contractInfoService.updateTemplate(contractInfo);
        return JsonResult.success();
    }
    /**
     * 普通用户转vip
     */
    public JsonResult toVip(String ids){
        List<String> idList = Utils.strToList(ids,",");
        for (int i =0;i<idList.size();i++){
            Integer contractId=Integer.valueOf(idList.get(i));
            String sql = "SELECT * FROM `customer_account` WHERE reg_account IN ( " +
                    "SELECT student_phone FROM `contract_info` WHERE contract_id = ? )";
            List<com.sdx.console.entity.CustomerAccount> list = sqlManager.execute(new SQLReady(sql,contractId), com.sdx.console.entity.CustomerAccount.class);
            if (list.size()>1){
                return  JsonResult.loginFail("505","会员信息 手机号码有重复！");
            }
            String cutomerid = list.get(0).getCustomerId();//用户的userid
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式
            //判断本身是不是龙卡用户
            //不是龙卡 ，插入vip
            List<RightCustomerRole> selectRightCustomerRole  = sqlManager.query(RightCustomerRole.class).andEq("customer_id",cutomerid).select();
            if (selectRightCustomerRole.size()==0){
                try {
                    RightCustomerRole rightCustomerRole = new RightCustomerRole();
                    rightCustomerRole.setCustomerId(cutomerid);
                    rightCustomerRole.setRoleId(1);
                    rightCustomerRole.setRightStatus(1);
                    rightCustomerRole.setOnceOnly(0);
                    //设置过期时间
                    Date data = simpleDateFormat.parse(String.valueOf(sqlManager.single(ContractInfo.class,contractId).getGraduateYear())+"-08-31 23:59:59");
                    rightCustomerRole.setExpiredDate(data);
                    //权限创建时间
                    rightCustomerRole.setCreateTime(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
                    rightCustomerRole.setRightSource(5);
                    rightCustomerRole.setRemark("一对一合同入单生成的会员");
                    sqlManager.insertTemplate(rightCustomerRole);
                } catch (ParseException e) {
                    return JsonResult.loginFail("506","生成龙卡用户失败！");
                }

            }else{ // 是龙卡用户，查看过期日期，判断是否需要更新日期
                if (selectRightCustomerRole.size()>1){
                    return JsonResult.loginFail("507","龙卡信息重复！");
                }
                try {
                    RightCustomerRole rightCustomerRole = selectRightCustomerRole.get(0);
                    Date newdata = simpleDateFormat.parse(String.valueOf(sqlManager.single(ContractInfo.class,contractId).getGraduateYear())+"-08-31 23:59:59");
                    if( newdata.after(rightCustomerRole.getExpiredDate())){//如果高考年份的8月31号比原来的日期大 ，更新日期
                        rightCustomerRole.setExpiredDate(newdata);
                        sqlManager.updateTemplateById(rightCustomerRole);
                    }
                } catch (ParseException e) {
                    return JsonResult.loginFail("508","更新龙卡的过期时间失败！");
                }
            }
        }

        return JsonResult.success();
    }

}
